<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2022-04-21
 * Time: 11:22:52
 * Info:
 */

namespace app\admin\controller\system;

use app\admin\annotation\ControllerAnnotation;
use app\admin\annotation\NodeAnotation;
use app\admin\controller\CommonController;
use support\Request;
use app\common\model\Admin as AdminModel;
use app\common\model\AuthGroup as AuthGroupModel;
use support\lib\Env;

/**
 * @ControllerAnnotation(title="管理员管理")
 * Class Node
 * @package app\admin\controller\system
 */
class AdminController extends CommonController
{

    /**
     * @NodeAnotation(title="管理员列表")
     */
    public function index(Request $request)
    {
        if ($request->isAjax()) {
            $limit = (int)$request->input('limit', 10);
            $page  = (int)$request->input('page', 1);
            $key   = $request->input('key');
            $first = (int)($page - 1) * $limit;
            $where = function ($query) use ($key) {
                if ( ! empty($key['username'])) {
                    $query->whereLike('username', '%'.$key['username'].'%');
                }
                if ( ! empty($key['nickname'])) {
                    $query->whereLike('nickname', '%'.$key['nickname'].'%');
                }
                if ( ! empty($key['email'])) {
                    $query->whereLike('email', '%'.$key['email'].'%');
                }
                if ( ! empty($key['role_id'])) {
                    $query->where('role_id', $key['role_id']);
                }
                if (isset($key['status']) && $key['status'] != '') {
                    $query->where('status', $key['status']);
                }
            };
            $total = AdminModel::where($where)->count();
            $list  = AdminModel::with([
                'authGroup' => function ($query) {
                    $query->Field('id,name');
                }
            ])->where($where)->limit($first, $limit)->select();
            foreach ($list as $k => $v) {
                $list[$k]['group_name'] = $v['authGroup']['name'];
                $list[$k]['logintime']  = date('Y-m-d H:i:s', $v['logintime']);
            }

            return success_json("ok", $list, $total);
        }

        $roleGroupName = AuthGroupModel::getGroupName();

        return view('admin/index', ['role_group_name' => $roleGroupName]);
    }

    /**
     * @NodeAnotation(title="添加管理员")
     */
    public function add(Request $request)
    {
        if ($request->isPost()) {
            $param = $request->post();
            $this->validate->rule([
                'username|登录名' => 'require|length:4,12|alpha',
                'password|密码'  => 'require|length:6,20|alphaDash',
                'role_id|角色组'  => 'require',
            ]);
            $this->validate->message([
                'username.require'   => '登录名不能为空',
                'username.length'    => '登录名长度必须4-12之间',
                'username.alpha'     => '登录名只能为字母',
                'password.require'   => '密码不能为空',
                'password.length'    => '密码长度必须在6-20之间',
                'password.alphaDash' => '密码只能是字母数字下划线_及破折号-',
                'role_id.require'    => '所属角色组不能为空',
            ]);
            if ( ! $this->validate->check($param)) {
                return error_json($this->validate->getError());
            }
            $res = AdminModel::manageAdd($param);
            if ($res['code'] == 200) {
                return success_json($res['msg']);
            } else {
                return error_json($res['msg']);
            }
        }
        $roleGroupName = AuthGroupModel::getGroupName();

        return view('admin/add', ['role_group_name' => $roleGroupName]);
    }

    /**
     * @NodeAnotation(title="获取管理员信息")
     */
    public function info(Request $request)
    {
        if ($request->isAjax()) {
            $id = $request->post('id');
            if (empty($id)) {
                return error_json('管理员id不能为空');
            }
            $res = AdminModel::getInfo($id);
            if ($res['code'] == 200) {
                return success_json($res['msg'], $res['data']);
            } else {
                return error_json($res['msg']);
            }
        }

        return view('admin/info');
    }

    /**
     * @NodeAnotation(title="更新管理员")
     */
    public function edit(Request $request)
    {
        if ($request->isPost()) {
            $param = $request->post();
            $this->validate->rule([
                'id|id'       => 'require',
                'role_id|角色组' => 'require',
            ]);
            $this->validate->message([
                'id.require'      => '管理员id不能为空',
                'role_id.require' => '所属角色组不能为空',
            ]);
            if ( ! $this->validate->check($param)) {
                return error_json($this->validate->getError());
            }
            $res = AdminModel::manageEdit($param);
            if ($res['code'] == 200) {
                return success_json($res['msg']);
            } else {
                return error_json($res['msg']);
            }
        }
        $id            = $request->get('id');
        $roleGroupName = AuthGroupModel::getGroupName();
        $data          = AdminModel::getInfo($id);

        return view('admin/edit', ['role_group_name' => $roleGroupName, 'data' => $data['data']]);
    }

    /**
     * @NodeAnotation(title="删除管理员")
     */
    public function delete(Request $request)
    {
        if ($request->isAjax()) {
            $id = $request->get('id');
            if (empty($id)) {
                return error_json('管理员id不能为空');
            }
            $res = AdminModel::manageDel($id);
            if ($res['code'] == 200) {
                return success_json($res['msg']);
            } else {
                return error_json($res['msg']);
            }
        }
    }

    /**
     * @NodeAnotation(title="更改状态")
     */
    public function status(Request $request)
    {
        if ($request->isAjax()) {
            $id  = $request->get('id');
            $val = $request->post('val', 1);
            if (empty($id)) {
                return error_json('管理员id不能为空');
            }
            $res = AdminModel::manageStatus($id, $val);
            if ($res['code'] == 200) {
                return success_json($res['msg']);
            } else {
                return error_json($res['msg']);
            }
        }
    }

    /**
     * @NodeAnotation(title="修改密码")
     */
    public function pass(Request $request)
    {
        if ($request->isPost()) {
            // 判断是否为演示环境
            if (Env::get('HUICMF.IS_DEMO', false) && $request->isPost()) {
                return error_json('演示环境下不允许修改');
            }

            $param = $request->all();
            if (empty($param['oldpwd'])) {
                return error_json('旧密码不能为空');
            }
            if (empty($param['newpwd'])) {
                return error_json('新密码不能为空');
            }
            $res = AdminModel::editPass($param);
            if ($res['code'] == 200) {
                return success_json($res['msg']);
            } else {
                return error_json($res['msg']);
            }
        }

        return view('admin/pass');
    }

}
